import React from "react"
import {message, Table, Form, Button, Select, Checkbox, Tag, Input} from 'antd'
import {
    fetchTableAndColumnsApi, updateColumns, fetchTableInfoApi, modifyTableInfoApi
} from "../api/projectConfig"
import {Config} from "../utils/Constants";
import ValidatePanel from "./ValidatePanel";
import RelationVerify from "./RelationVerify";
import {getDictList} from "../api/sysDict";

const FormItem = Form.Item;
const Option = Select.Option;

class Domain extends React.Component {

    projectId;
    fileId;
    state = {
        tableColumns: [],
        voFields: [],
        tableList: [],

        dataTypeMap: {}, // table row edit

        voList: [],

        /** form data */
        curd: [],
        genTable: '',
        id: 0,
        relationVisible: false,
        relationData: {},
        dictList: [{id: 0, name: '无'}],
        tableName: '',
        routePath: '',
    };

    constructor(props) {
        super(props);
        this.projectId = this.props.projectId

    }

    componentDidMount() {


        this.fileId = this.props.fileNode.fileId;

        this.changeSuperSelected(this.fileId);


        getDictList(1, 10000).then(res => {
            let list = res.data.data.rows || [];
            this.setState({dictList: [...this.state.dictList, ...list]});
        })

        fetchTableInfoApi(this.fileId).then(res => {

            let data = res.data.data;
            let {id, curd, genTable, tableName,routePath} = data;

            if (curd !== "no") {
                curd = curd.split(",");
            } else {
                curd = [];
            }

            this.setState({...this.state, id, curd, genTable, tableName,routePath})
        });

    }

    changeSuperSelected = (value) => {
        if (value > 0) {
            fetchTableAndColumnsApi(value).then(res => {
                this.setState({...this.state, tableColumns: res.data.data.columns})
            })
        } else {
            this.setState({...this.state, tableColumns: []})
        }
    };

    saveFileInfo = () => {

        this.props.form.validateFieldsAndScroll((err, formData) => {
            if (!err) {
                let {curd} = formData;
                let newCurd;
                if (curd.length > 0) {
                    newCurd = curd.join(",");
                } else {
                    newCurd = "no";
                }

                let postData = {id: this.fileId, ...formData, curd: newCurd};
                modifyTableInfoApi(postData).then(res => {
                    message.success('保存成功！');
                    this.setState({curd: curd});
                })
            }})

    };


    checkChange = (name, value, id) => {
        let obj = {'id': id};
        obj[name] = value ? 'yes' : 'no';
        console.log(this.fileId)
        updateColumns(obj).then((res) => {
            message.success('修改成功！');

            this.changeSuperSelected(this.fileId);
        })
    }

    showValidatePanel = row => {
        this.validatePanel.showPanel(row);
    }

    selectQuery = obj => {
        updateColumns(obj).then((res) => {
            message.success('修改成功！');
            this.changeSuperSelected(this.fileId);
        })
    }

    handleRelationCancel = () => {
        this.setState({relationVisible: false, relationDate: {}})
        this.changeSuperSelected(this.fileId);
    }

    showRelation = row => {
        this.setState({relationVisible: true, relationData: row})
    }


    render() {
        const {curd, relationVisible, relationData, dictList} = this.state;

        var ignoreVo = Config.VO_IGNORE.indexOf(this.state.name) > -1;

        const tableFieldColumns = [{
            title: 'name',
            dataIndex: 'name',
            key: 'name',
        }, {
            title: 'db type',
            dataIndex: 'mysqlType',
            key: 'type',
        }, {
            title: 'comment',
            dataIndex: 'comment',
            key: 'comment',
        }];

        if (curd.length > 0) {
            let colors = ['magenta', 'red', 'volcano', 'orange', 'gold', 'gold', 'green', 'cyan', 'blue', 'geekblue', 'purple'];
            tableFieldColumns.push(...[
                {
                    title: 'List',
                    dataIndex: 'l',
                    key: 'l',
                    render: (text, record) => <Checkbox checked={text === "yes"}
                                                        onChange={(e) => this.checkChange('l', e.target.checked, record.id)}/>
                }, {
                    title: 'C',
                    dataIndex: 'c',
                    key: 'c',
                    render: (text, record) => <Checkbox checked={text === "yes"}
                                                        onChange={(e) => this.checkChange('c', e.target.checked, record.id)}/>
                }, {
                    title: 'U',
                    dataIndex: 'u',
                    key: 'u',
                    render: (text, record) => <Checkbox checked={text === "yes"}
                                                        onChange={(e) => this.checkChange('u', e.target.checked, record.id)}/>
                }, {
                    title: 'R',
                    dataIndex: 'r',
                    key: 'r',
                    render: (text, record) => <Checkbox checked={text === "yes"}
                                                        onChange={(e) => this.checkChange('r', e.target.checked, record.id)}/>
                }, {
                    title: 'verify',
                    dataIndex: 'v',
                    key: 'v',
                    render: (text, row, index) => {
                        let arr = [];
                        // 处理下内容
                        if (text) {
                            arr = eval(text);
                        }
                        return (<span>
                                {arr.map((v, ii) => {
                                    let colorIndex = parseInt(Math.random() * colors.length) % colors.length;
                                    return <Tag key={index + '_' + ii} color={colors[colorIndex]}>{v}</Tag>
                                })}

                            <Button icon={"plus"} onClick={() => {
                                this.showValidatePanel(row)
                            }} type="primary" size="small"/>
                </span>)
                    }
                }, {
                    title: 'query',
                    dataIndex: 'q',
                    key: 'q',
                    render: (text, record, index) => {
                        return <Select defaultValue={text} style={{width: 100}}
                                       onChange={(e) => this.selectQuery({'id': record.id, 'q': e})}>
                            <Option value="no">无</Option>
                            <Option value="EqualTo">相等</Option>
                            <Option value="NotEqualTo">不相等</Option>
                            <Option value="Like">模糊匹配</Option>
                            <Option value="NotLike">反模糊匹配</Option>
                            <Option value="LessThan">小于</Option>
                            <Option value="GreaterThan">大于</Option>
                            <Option value="LessThanOrEqualTo">小于等于</Option>
                            <Option value="GreaterThanOrEqualTo">大于等于</Option>
                            <Option value="Between">之间</Option>
                            <Option value="In">包含</Option>
                            <Option value="NotIn">不包含</Option>
                        </Select>
                    }
                }, {
                    title: '字典类型',
                    dataIndex: 'dictId',
                    key: 'dictId',
                    render: (text, record, index) => {
                        return <Select defaultValue={text} style={{width: 100}}
                                       onChange={(e) => this.selectQuery({'id': record.id, 'dictId': e})}>
                            {dictList.map(val => <Option value={val.id}>{val.name}</Option>)}
                        </Select>
                    }
                }, {
                    title: 'label',
                    dataIndex: 'label',
                    key: 'label',
                    render: (text, record) => <Input style={{width: 100}} defaultValue={text}
                                                     onBlur={(e) => this.selectQuery({
                                                         'id': record.id,
                                                         'label': e.target.value
                                                     })}/>
                }, {
                    title: '表单类型',
                    dataIndex: 'formType',
                    key: 'formType',
                    render: (text, record, index) => {
                        return <Select defaultValue={text} style={{width: 100}}
                                       onChange={(e) => this.selectQuery({'id': record.id, 'formType': e})}>
                            <Option value="text">文本框</Option>
                            <Option value="textarea">富文本</Option>
                            <Option value="select">下拉框</Option>
                            <Option value="checkbox">多选框</Option>
                            <Option value="digit">数字输入框</Option>
                            <Option value="password">密码控件</Option>
                            <Option value="dateTime">时间控件</Option>
                        </Select>
                    }
                }, {
                    title: '表关联',
                    dataIndex: 'relationJson',
                    key: 'relationJson',
                    render: (text, row, index) => {
                        return <Button onClick={() => {
                            this.showRelation(row)
                        }} type="primary" size="small">{text !== 'no' ? "查看" : "添加"}</Button>
                    }
                }
            ])
        }


        const formItemLayout = {
            labelCol: {
                xs: {span: 12},
                sm: {span: 3},
            },
            wrapperCol: {
                xs: {span: 12},
                sm: {span: 10},
            },
        }
        const {getFieldDecorator,getFieldValue} = this.props.form


        console.info('ignoreVo=' + ignoreVo + ',name=' + this.state.name)

        return (
            <div>
                <span className="code_key">package</span>
                <Form className="form_item_4" onSubmit={this.saveFileInfo}>
                    <FormItem {...formItemLayout} label="是否CURD">
                        {getFieldDecorator('curd', {
                            initialValue: this.state.curd
                        })(
                            <Select
                                mode="multiple"
                                allowClear
                                style={{width: '100%'}}
                                placeholder="不选择默认为否"
                            >
                                <Option key="1" value="c">C</Option>
                                <Option key="2" value="u">U</Option>
                                <Option key="3" value="r">R</Option>
                                <Option key="4" value="d">D</Option>
                            </Select>
                        )}
                    </FormItem>

                    {getFieldValue("curd").length > 0 &&
                    <>
                        <FormItem {...formItemLayout} label="是否生成Table">
                            {getFieldDecorator('genTable', {
                                initialValue: this.state.genTable,
                                rules: [{required: true, message: '请选择是否生成!'}],
                            })(
                                <Select
                                    allowClear
                                    style={{width: '100%'}}
                                    placeholder="请选择"
                                >
                                    <Option key="1" value="yes">生成</Option>
                                    <Option key="2" value="no">不生成</Option>
                                </Select>
                            )}
                        </FormItem>

                        <FormItem {...formItemLayout} label="表格名称">
                            {getFieldDecorator('tableName', {
                                initialValue: this.state.tableName,
                                rules: [{required: true, message: '请输入表格中文名称!'}],
                            })(<Input placeholder="请输入表格中文名称"/>)}
                        </FormItem>

                        <FormItem {...formItemLayout} label="路由地址">
                            {getFieldDecorator('routePath', {
                                initialValue: this.state.routePath,
                                rules: [{required: true, message: '请输入路由地址!'}],
                            })(<Input placeholder="请输入路由地址"/>)}
                        </FormItem>
                    </>
                    }
                    <Button type="primary" onClick={this.saveFileInfo} style={{
                        position: "absolute",
                        right: "20px",
                        top: "60px",
                        display: ignoreVo ? 'none' : ''
                    }}>保存</Button>
                </Form>
                <hr/>
                <h3>table</h3>
                <Table rowKey={record => record.id} className={'table-columns-tab'} dataSource={this.state.tableColumns}
                       columns={tableFieldColumns} pagination={false}/>
                <hr/>

                {/* 设置参数验证 */}
                <ValidatePanel key="validatePanel_key" type="vo"
                               hideValidatePanel={() => this.changeSuperSelected(this.fileId)} onRef={(ref) => {
                    this.validatePanel = ref
                }}/>
                {/* 表关联 */}
                {relationVisible &&
                <RelationVerify visible={relationVisible} projectId={this.projectId} relationData={relationData}
                                handleCancel={this.handleRelationCancel}/>
                }
            </div>
        )
    }
}


const _Domain = Form.create()(Domain)
export default _Domain
